import cTitle from "components/title";
import { Toast } from "vant";
// import { Toast } from 'vant';

const documentElement = document.documentElement;
const body = document.body;
// 将整数转换成 时：分：秒的格式
function realFormatSecond(second) {
  var secondType = typeof second;

  if (secondType === 'number' || secondType === 'string') {
    second = parseInt(second);

    var hours = Math.floor(second / 3600);
    second = second - hours * 3600;
    var mimute = Math.floor(second / 60);
    second = second - mimute * 60;

    return hours + ':' + ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2);
  } else {
    return '0:00:00';
  }
}
export default {
  data() {
    return {
      active: "",
      id: "0",
      banner: "",
      title: "",
      datas: [],
      categories: [],
      isLoadMore: true,
      page: 1,
      total_page: 0,
      show1: false,
      noNotice: false,
      article_pay: '',
      searchText: '',
      value: 0,
      sliderTime: 0,
      playInd: null,
      currentTime: '',
      postStart: false,
      sliderShow:false,

      show_video_popup:false,
      video_info:{},
      isPlay:true,
    };
  },
  activated() {
    this.initData();

    //获取数据
    this.getNetData('true');
    window.addEventListener("scroll", this.handleScroll);
    console.log(this.fun.getKey("class_id"),"==111===1=1=1=1=1");

  },
  deactivated() {
    this.activeName = "-1";
    window.removeEventListener("scroll", this.handleScroll);
  },
  mounted() {
    if (this.fun.getKey("class_id")) {
      this.active = "";
    } else {
      this.active = 0;
    }
  },

  methods: {
    // 拖动
    handleTouchStart(e, i) {
      this.$refs[`audio${i}`][0].currentTime = parseInt(this.datas[i].maxTime * (e / 100));
      this.$refs[`audio${i}`][0].play()
    },
    onLoadedmetadata(res, i) {
      if(res.target.duration){
        this.$set(this.datas[i], 'maxTime', parseInt(res.target.duration))
      }
    },
    onTimeupdate(res, i) {
      this.currentTime = res.target.currentTime;
      let time = parseInt(this.currentTime / this.datas[i].maxTime * 100);
      if (time >= 100) {
        this.sliderTime = 100;
      } else {
        this.sliderTime = time;
      }
    },
    async startPlayOrPause(item, i) {
      console.log('ddddddddd',item.id, i,"item",item)
      let check = await this.checkPrivilege(item.id)
      if(check.result == 0){
        Toast(check.msg);
        return
      }
      if (item.has_one_article_pay) {
        if (!item.has_one_record) {
          this.$router.push(this.fun.getUrl("payList", { id: item.id }));
          return
        }
      }
      if (this.playInd != i) {
        this.postStart = false;
      }
      if(!this.sliderShow) this.sliderShow = true;
      this.playInd = i;
      console.log(this.datas,"datas=====")
      this.video_info = check.data;
      this.video_info.audio_seconds = item.audio_seconds;
      this.show_video_popup = true;
      this.isPlay = false;
      console.log(this.video_info,"this.video_info===");
      for (let k = 0; k < this.datas.length; k++) {
        if (k == i) {
          if (this.$refs[`audio${i}`][0].onplay) {
            console.log("0000")
            this.pause(i);
          } else {
            console.log("1111")
            this.play(i);
          }
        } else {
          console.log("22222222")
          // this.$refs[`audio${k}`][0].load();
          this.$set(this.datas[k], 'playStatus', false)
          this.$refs[`audio${k}`][0].pause();
        }
      }
    },
    checkPrivilege(id){
      return new Promise((resolve, reject)=>{
        $http.get("plugin.article.api.article.get-article", { article_id: id },).then(
          response => {
            if (response.result == 1) {
              resolve(response)
            }else{
              resolve(response)
            }
          },
          function (response) {
            console.log(response);
          }
        );
      })
    },
    // 播放结束
    endedMethod() {
      console.log('endedMethod')
      this.isPlay = true;
      this.postStart = false;
    },
    // 播放音频
    play(i) {
      this.$refs[`audio${i}`][0].play();
      this.startPostMethod();
    },
    // 暂停音频
    pause(i) {
      this.$refs[`audio${i}`][0].pause();
      this.isPlay = true;
      this.postStart = true;
    },
    // 当音频暂停
    onPause(i) {
      if(this.datas.length >0){
        this.$set(this.datas[i], 'playStatus', false)
      }
    },
    onPlay(i) {
      this.$set(this.datas[i], 'playStatus', true)
    },
    shareTap(item) {
      this.$dialog.alert({ message: "请点击右上角微信分享" });
      let mid = this.fun.getKeyByMid();
      let _url = this.fun.getSiteRoot() + "/addons/yun_shop/?menu#/VoiceDetail/"+item.id+"?i=" + this.fun.getKeyByI() + "&mid=" + mid;
      if(this.$route.query.taskID){
        _url += `&taskID=${this.$route.query.taskID}&taskDay=${this.$route.query.taskDay}&task_type=article`;
      }
      this.fun.wxShare(
        "",
        {},
        {
          link: _url,
          title:item.title,
          imgUrl:item.thumb,
          description:item.desc
        },
        data => {}
      );
      console.log(_url)
    },
    toEssay() {
      this.$router.push(this.fun.getUrl("payEssay"));
    },
    tapClose(){
      this.sliderShow =false;
    },
    initData() {
      this.page = 1;
      this.total_page = 0;
      this.isLoadMore = true;
      this.datas = [];
      this.sliderShow = false;
      this.sliderTime = 0;
    },
    startPostMethod() {
      if (this.postStart == false) {
        console.log('没有暂停')
        $http.get("plugin.article.api.article.clickAudioViews", { article_id: this.datas[this.playInd].id },).then(
          response => {
            if (response.result == 1) {
              console.log('完成',response)
              this.$set(this.datas[this.playInd], 'virtual_audio_views', response.data.virtual_audio_views)
            }
          },
          function (response) {
            console.log(response);
          }
        );
      } else {
        console.log('暂停过 postStart = true')
      }
    },
    //获取滚动条当前的位置
    getScrollTop() {
      var scrollTop = 0;
      if (documentElement && documentElement.scrollTop) {
        scrollTop = documentElement.scrollTop;
      } else if (body) {
        scrollTop = body.scrollTop;
      }
      return scrollTop;
    },
    //获取当前可视范围的高度
    getClientHeight() {
      var clientHeight = 0;
      if (body.clientHeight && documentElement.clientHeight) {
        clientHeight = Math.min(
          body.clientHeight,
          documentElement.clientHeight
        );
      } else {
        clientHeight = Math.max(
          body.clientHeight,
          documentElement.clientHeight
        );
      }
      return clientHeight;
    },
    //获取文档完整的高度
    getScrollHeight() {
      return Math.max(body.scrollHeight, documentElement.scrollHeight);
    },

    handleScroll() {
      //滚动事件触发
      if (
        this.getScrollTop() + this.getClientHeight() + 105 >
        this.getScrollHeight()
      ) {
        // console.log('下拉刷新了')
        //此处发起请求
        if (this.isLoadMore) {
          this.getMoreData();
        } else {
          console.log("没有更多数据");
        }
      }
    },

    searchArt() {
      this.getNetData();
    },
    enterSearch(event) {
      if (event.keyCode === 13) {
        //如果按的是enter键
        event.preventDefault();
        this.getNetData();
      }
    },

    //获取数据
    getNetData(flag) {
      let that = this;
      if (this.fun.getKey("class_id") && flag) {
        this.id = this.fun.getKey("class_id");
      }
      let json = {
        category_id: this.id,
        keyword: encodeURIComponent(this.searchText),
        page: 1,
      };
      $http.get("plugin.article.api.article.get-articles", json, "获取中").then(
        response => {
          if (response.result == 1) {
            this.noNotice = false;
            that.total_page = response.data.articles.last_page;
            if (!that.total_page) {
              that.total_page = 0;
            }
            that.isLoadMore = true;
            if (response.data.categories.length <= 0) {
              this.noNotice = true;
            }
            // that.banner = response.data.banner;
            that.title = response.data.title;
            that.datas = response.data.articles.data;
            that.categories = response.data.categories;
            that.fun.setWXTitle(response.data.title);
            that.article_pay = response.data.article_pay;
            if (this.fun.getKey("class_id") && flag) {
              let child = this.categories.some((item,index) => {
                if(item.id == this.fun.getKey("class_id")) {
                  that.active = index + 1;
                }
                return item.id == this.fun.getKey("class_id")
              });
              if(!child) {
                that.active = '0';
              }
              this.$nextTick(() => {
                this.$refs.act.resize();
              })
            }
          } else {
            Toast(response.msg);
            this.noNotice = true;
          }
        },
        function (response) {
          console.log(response);
        }
      );
    },

    getMoreData(page) {
      let that = this;

      that.isLoadMore = false; // 防止多次请求分页数据
      if (this.page >= this.total_page) {
        console.log("getMoreData", this.total_page);
        return;
      } else {
        this.page = this.page + 1;
        let json = {
          category_id: this.id,
          keyword: this.searchText,
          page: this.page,
          is_decorate: false
        };
        $http
          .get("plugin.article.api.article.get-articles", json, "加载中")
          .then(
            function (response) {
              if (response.result === 1) {
                that.isLoadMore = true;
                that.total_page = response.data.articles.last_page;

                that.datas = that.datas.concat(response.data.articles.data);
              } else {
                that.page = that.page - 1;
                that.isLoadMore = false;
                return;
              }
            },
            function (response) {
              // error callback
            }
          );
      }
    },

    toNoticeInfo(item) {
      if (item.has_one_article_pay) {
        if (item.has_one_record) {
          if (item.type == 1) {
            if(this.$route.query.taskID){
              this.$router.push(this.fun.getUrl("VoiceDetail", { article_id: item.id },{taskID:this.$route.query.taskID,taskDay:this.$route.query.taskDay,task_type:'article'}));
            }else{
              this.$router.push(this.fun.getUrl("VoiceDetail", { article_id: item.id }));
            }
          } else {
            if(this.$route.query.taskID){
              this.$router.push(this.fun.getUrl("articleContent", { id: item.id },{taskID:this.$route.query.taskID,taskDay:this.$route.query.taskDay,task_type:'article'}));
            }else{
              this.$router.push(this.fun.getUrl("articleContent", { id: item.id }));
            }
          }
        } else {
          this.$router.push(this.fun.getUrl("payList", { id: item.id }));
          return;
        }
      } else {
        if (item.type == 1) {
          if(this.$route.query.taskID){
            this.$router.push(this.fun.getUrl("VoiceDetail", { article_id: item.id },{taskID:this.$route.query.taskID,taskDay:this.$route.query.taskDay,task_type:'article'}));
          }else{
            this.$router.push(this.fun.getUrl("VoiceDetail", { article_id: item.id }));
          }
        } else {
          if(this.$route.query.taskID){
            this.$router.push(this.fun.getUrl("articleContent", { id: item.id },{taskID:this.$route.query.taskID,taskDay:this.$route.query.taskDay,task_type:'article'}));
          }else{
            this.$router.push(this.fun.getUrl("articleContent", { id: item.id }));
          }
        }
        return;
      }
    },
    onClick(index, title) {
      this.initData();
      console.log(index);
      // let tab = document.getElementById("tab");
      // let tabChild = tab.getElementsByClassName("tabChild");
      // console.log(tab,tabChild)
      // this.id = tabChild[index].getAttribute("id");
      if (index == 0) {
        this.id = 0;
      } else {
        this.id = this.categories[index - 1].id;
      }
      this.getNetData();
    }
  },
  filters: {
    // 将整数转化成时分秒
    formatSecond(second = 0) {
      return realFormatSecond(second);
    }
  },
  components: { cTitle }
};
